package ch.fusun.baron.data;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

/**
 * Abstract implementation of a Data Provider. Provides utility for listeners
 */
public abstract class AbstractDataProvider implements DataProvider {

	private transient final List<DataListener> listeners = new LinkedList<DataListener>();

	@Override
	public void addDataListener(DataListener listener) {
		listeners.add(listener);
	}

	@Override
	public void addDataListenerIfNotAlready(DataListener listener) {
		if (!listeners.contains(listener)) {
			addDataListener(listener);
		}
	}

	@Override
	public void removeDataListener(DataListener listener) {
		listeners.remove(listener);
	}

	@Override
	public Collection<? extends DataListener> getListeners() {
		return listeners;
	}

	/**
	 * Updates all registered listeners
	 */
	protected void updateAllListeners(DataUpdate update) {
		for (DataListener listener : listeners) {
			listener.dataChanged(update);
		}
	}

	@Override
	public void removeAllListeners() {
		listeners.clear();
	}
}
